package com.share.demo.service;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.share.demo.dao.UserRepository;
import com.share.demo.domain.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * caifan 2017/10/3
 */
@Service
@Slf4j
public class UserService {
    @Autowired
    private UserRepository userRepository;

    @Transactional
    public void insertUser(User user) {
        /*
         * 不存在则执行添加 存在则修改 hibernate merge
         */
        userRepository.save(user);
    }

    @Transactional
    @DS("ds2")
    public void insertUser2(User user) {
        /*
         * 不存在则执行添加 存在则修改 hibernate merge
         */
        userRepository.save(user);
    }

    public List<User> findAllUser() {
        List<User> userList = new ArrayList<>();
        Iterable<User> userIterable = userRepository.findAll();
        Iterator<User> iterator = userIterable.iterator();
        while(iterator.hasNext()) {
            User user = iterator.next();
            userList.add(user);
        }
        return userList;
    }

    public Page<User> findUserPage() {
        PageRequest pageable = new PageRequest(0, 2);
        return userRepository.findAll(pageable);
    }

   /* public void updateUser(User user) {
        userRepository.updateUser(user);
    }*/

   @Transactional
    public void updateUserAgeById(Long id, Integer age) {
        userRepository.updateUserAge(id, age);
    }

    @Transactional
    public void deleteUserById(Long id) {
        userRepository.deleteUserById(id);
    }

    public User findUserById(Long id) {
//       log.info("service getUser id:{}", id);
        return userRepository.findUserById(id);
    }
}
